//
//  CommitsViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/3/10.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import ThPullRefresh

class CommitsViewController: UITableViewController {
    var nameSpace: String!
    var commits: [GTCommit] = []
    var refName: String!
    var projectID: Int!
    var projectCell: ProjectCell!
    
    var page: NSInteger = 1
    var isHeadRefresh: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        self.title = refName
        
        self.tableView.registerNib(UINib(nibName: "ProjectCell", bundle: nil), forCellReuseIdentifier: "projectCell")
        projectCell = self.tableView.dequeueReusableCellWithIdentifier("projectCell") as! ProjectCell
        
        self.fetchForCommit()
        self.tableView.tableFooterView = UIView()
        self.tableView.addHeadRefresh(self) { () -> () in
            
            self.isHeadRefresh = true
            self.page = 1
            self.fetchForCommit()
        }
        self.tableView.addFootRefresh(self) { () -> () in
            
            self.isHeadRefresh = false
            ++self.page
            self.fetchForCommit()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //列表
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if commits.count > 0 {
            return commits.count
        }
        return 0
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if commits.count > 0 {
            let commit = commits[indexPath.row]

            projectCell!.contentLabel.text = commit.title
            let height = projectCell.contentLabel.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
            
            return 75 + height
        }
        return 100
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let projectCell = tableView.dequeueReusableCellWithIdentifier("projectCell", forIndexPath: indexPath) as? ProjectCell
        
        if indexPath.row < commits.count {
            let commit = commits[indexPath.row]
            
            projectCell?.getProjectCommit(commit)
        }
        
        return projectCell!
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        let diffVC = CommitDiffViewController()
        diffVC.nameSpace = nameSpace
        diffVC.commit = commits[indexPath.row]
        diffVC.projectID = self.projectID
        self.navigationController?.pushViewController(diffVC, animated: true)
    }
    
    
    //获取数据
    func fetchForCommit() {
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        
        let strUrl = "https://git.oschina.net/api/v3/projects/\(nameSpace)/repository/commits?page=\(page)&ref_name=\(refName)&private_token=\(private_token)"
        
        if self.isHeadRefresh {
            self.commits.removeAll(keepCapacity: Bool())
        }
        
        Alamofire.Manager.sharedInstance.request(Method.GET, strUrl).responseJSON { response in
            if let results = response.result.value {
                let jsonArray = JSON(results).array!
                
                for i in 0 ..< jsonArray.count {
                    
                    let commit = GTCommit(json: jsonArray[i])
                    self.commits.append(commit)
                }
                
                self.tableView.reloadData()
                self.tableView.tableHeadStopRefreshing()
                self.tableView.tableFootStopRefreshing()
            }
        }
    }
}
